﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;
using Module;

namespace HeThongSpa.QuanTriHeThong.DanhMuc
{
    public partial class DanhMucTaiKhoan : Page
    {
        private const int PageSize = 20;

        private Module.QuanTriHeThong.DanhMuc.DanhMucTaiKhoan _danhMucTaiKhoan =
            new Module.QuanTriHeThong.DanhMuc.DanhMucTaiKhoan();

        private readonly SelectAll _selectAll = new SelectAll();

        private int _totalrow;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack) return;
            if (Session["username"] == null)
                Response.RedirectToRoute("DangNhap");
            else
            {
                SelectAllChucVu();
                SelectAllCuaHang();
                LoadPage();
            }
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            ViewState["CheckRefresh"] = Session["CheckRefresh"];
        }

        private void SelectAllChucVu()
        {
            ddlChucVu.DataSource = _selectAll.SelectAllChucVu();
            ddlChucVu.DataTextField = "TenChucVu";
            ddlChucVu.DataValueField = "MaChucVu";
            ddlChucVu.DataBind();
            ddlChucVu.Items.Insert(0, new ListItem("Chọn", ""));
        }

        private void SelectAllCuaHang()
        {
            ddlCuaHang.DataSource = _selectAll.SelectAllCuaHang();
            ddlCuaHang.DataTextField = "TenCuaHang";
            ddlCuaHang.DataValueField = "MaCuaHang";
            ddlCuaHang.DataBind();
            ddlCuaHang.Items.Insert(0, new ListItem("Chọn", ""));
        }

        private void LoadPage()
        {
            _danhMucTaiKhoan = new Module.QuanTriHeThong.DanhMuc.DanhMucTaiKhoan();
            if (hfTimKiem.Value.Equals("true"))
            {
                _danhMucTaiKhoan.TaiKhoan = txtTenTaiKhoan.Text.Trim();
                _danhMucTaiKhoan.HoTen = txtHoTen.Text.Trim();
                _danhMucTaiKhoan.SoCMTND = txtSoCMTND.Text.Trim();
                _danhMucTaiKhoan.MaChucVu = ddlChucVu.SelectedValue.Trim();
                _danhMucTaiKhoan.MaCuaHang = ddlCuaHang.SelectedValue.Trim();
            }
            gvDanhMuc.DataSource = _danhMucTaiKhoan.SelectAll(_danhMucTaiKhoan,
                Convert.ToInt32(hfPageIndex.Value.Trim()),
                PageSize, out _totalrow);
            gvDanhMuc.DataBind();
            GeneratePager(_totalrow, PageSize, Convert.ToInt32(hfPageIndex.Value.Trim()));
            Session["CheckRefresh"] = Server.UrlEncode(DateTime.Now.ToString(CultureInfo.InvariantCulture));
        }

        protected void btnLuu_Click(object sender, EventArgs e)
        {
            if (Session["username"] == null)
                Response.RedirectToRoute("DangNhap");
            else
            {
                if (Session["CheckRefresh"].ToString() == ViewState["CheckRefresh"].ToString())
                {
                    _danhMucTaiKhoan.MaNhanVien = hfMaNhanVien.Value.Trim();
                    _danhMucTaiKhoan.HoTen = txtHoTen.Text.Trim();
                    _danhMucTaiKhoan.NgaySinh = Convert.ToDateTime(DateTime.ParseExact(txtNgaySinh.Text.Trim(), "dd-MM-yyyy", null).ToString("yyyy-MM-dd"));
                    _danhMucTaiKhoan.SoCMTND = txtSoCMTND.Text.Trim();
                    _danhMucTaiKhoan.DiaChi = txtDiaChi.Text.Trim();
                    _danhMucTaiKhoan.SoDienThoai = txtDienThoai.Text.Trim();
                    _danhMucTaiKhoan.MaChucVu = ddlChucVu.SelectedValue.Trim();
                    _danhMucTaiKhoan.MaCuaHang = ddlCuaHang.SelectedValue.Trim();
                    if (string.IsNullOrEmpty(_danhMucTaiKhoan.MaNhanVien))
                    {
                        _danhMucTaiKhoan.TaiKhoan = txtTenTaiKhoan.Text.Trim();
                        //if (!_danhMucTaiKhoan.Insert(_danhMucTaiKhoan, Session["username"].ToString().Trim()))
                        ClientScript.RegisterClientScriptBlock(typeof(string), "alert",
                            "bootbox.alert('Cập nhật thất bại, vui lòng thử lại.')", true);
                    }
                    else
                    {
                        _danhMucTaiKhoan.TaiKhoan = Session["username"].ToString().Trim();
                        if (!_danhMucTaiKhoan.Update(_danhMucTaiKhoan))
                            ClientScript.RegisterClientScriptBlock(typeof(string), "alert",
                                "bootbox.alert('Cập nhật thất bại, vui lòng thử lại.')", true);
                    }
                }
                ResetPage();
            }
        }

        protected void btnTimKiem_Click(object sender, EventArgs e)
        {
            txtTenTaiKhoan.Enabled = true;
            ddlCuaHang.Enabled = true;
            hfTimKiem.Value = "true";
            hfPageIndex.Value = "1";
            LoadPage();
        }

        protected void btnNhapLai_Click(object sender, EventArgs e)
        {
            ResetPage();
        }

        protected void gvDanhMuc_OnRowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType != DataControlRowType.DataRow ||
                (e.Row.RowState != DataControlRowState.Normal && e.Row.RowState != DataControlRowState.Alternate))
                return;
            var checkId = (CheckBox)e.Row.Cells[0].FindControl("check_id");
            var checkallId = (CheckBox)gvDanhMuc.HeaderRow.FindControl("checkall_id");
            checkId.Attributes["onclick"] = string.Format
                (
                    "javascript:checkClick(this,'{0}');",
                    checkallId.ClientID
                );
        }

        protected void btnSua_Click(object sender, EventArgs e)
        {
            if (Session["username"] == null)
                Response.RedirectToRoute("DangNhap");
            else
            {
                if (Session["CheckRefresh"].ToString() != ViewState["CheckRefresh"].ToString())
                    ResetPage();
                else
                {
                    hfMaNhanVien.Value = ((LinkButton)sender).CommandArgument;
                    var dt = _danhMucTaiKhoan.SelectByMaNhanVien(hfMaNhanVien.Value.Trim());
                    if (dt.Rows.Count <= 0) return;
                    txtTenTaiKhoan.Text = dt.Rows[0]["TaiKhoan"].ToString().Trim();
                    txtTenTaiKhoan.Enabled = false;
                    txtHoTen.Text = dt.Rows[0]["HoTen"].ToString().Trim();
                    txtHoTen.Focus();
                    txtNgaySinh.Text = Convert.ToDateTime(dt.Rows[0]["NgaySinh"].ToString().Trim()).ToString("dd-MM-yyyy");
                    txtSoCMTND.Text = dt.Rows[0]["SoCMTND"].ToString().Trim();
                    txtDienThoai.Text = dt.Rows[0]["SoDienThoai"].ToString().Trim();
                    txtDiaChi.Text = dt.Rows[0]["DiaChi"].ToString().Trim();
                    ddlChucVu.SelectedValue = dt.Rows[0]["MaChucVu"].ToString().Trim();
                    ddlCuaHang.SelectedValue = dt.Rows[0]["MaCuaHang"].ToString().Trim();
                    ddlCuaHang.Enabled = false;
                }
            }
        }

        protected void dlPager_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if (e.CommandName != "PageNo") return;
            hfPageIndex.Value = e.CommandArgument.ToString();
            LoadPage();
            e.Item.Attributes.Add("disabled", "disabled");
        }

        public void GeneratePager(int totalRowCount, int pageSize, int currentPage)
        {
            const int totalLinkInPage = 4;
            var totalPageCount = (int)Math.Ceiling((decimal)totalRowCount / pageSize);

            var startPageLink = Math.Max(currentPage - (int)Math.Floor((decimal)totalLinkInPage / 2), 1);
            var lastPageLink = Math.Min(startPageLink + totalLinkInPage - 1, totalPageCount);

            if ((startPageLink + totalLinkInPage - 1) > totalPageCount)
            {
                lastPageLink = Math.Min(currentPage + (int)Math.Floor((decimal)totalLinkInPage / 2), totalPageCount);
                startPageLink = Math.Max(lastPageLink - totalLinkInPage + 1, 1);
            }

            var pageLinkContainer = new List<ListItem>();

            if (startPageLink != 1)
            {
                pageLinkContainer.Add(new ListItem("«", "1", currentPage != 1));
            }
            for (var i = startPageLink; i <= lastPageLink; i++)
            {
                pageLinkContainer.Add(new ListItem(i.ToString(CultureInfo.InvariantCulture),
                    i.ToString(CultureInfo.InvariantCulture), currentPage != i));
            }
            if (lastPageLink != totalPageCount)
                pageLinkContainer.Add(new ListItem("»", totalPageCount.ToString(CultureInfo.InvariantCulture),
                    currentPage != totalPageCount));

            dlPager.DataSource = pageLinkContainer;
            dlPager.DataBind();
        }

        private void ResetPage()
        {
            hfMaNhanVien.Value = "";
            txtTenTaiKhoan.Text = string.Empty;
            txtTenTaiKhoan.Enabled = true;
            txtHoTen.Text = string.Empty;
            txtNgaySinh.Text = string.Empty;
            txtSoCMTND.Text = string.Empty;
            txtDienThoai.Text = string.Empty;
            txtDiaChi.Text = string.Empty;
            ddlCuaHang.SelectedValue = string.Empty;
            ddlCuaHang.Enabled = true;
            hfTimKiem.Value = "false";
            hfPageIndex.Value = "1";
            LoadPage();
        }

        protected void check_IsActive_CheckedChanged(object sender, EventArgs e)
        {
            if (Session["username"] == null)
                Response.RedirectToRoute("DangNhap");
            else
            {
                if (Session["CheckRefresh"].ToString() != ViewState["CheckRefresh"].ToString())
                    ResetPage();
                else
                {
                    var cb = ((CheckBox)sender);
                    var row = (GridViewRow)cb.NamingContainer;
                    if (row == null) return;
                    var rowindex = row.RowIndex;
                    var dataKey = gvDanhMuc.DataKeys[rowindex];
                    if (dataKey == null) return;
                    if (dataKey.Values == null) return;
                    var manhanvien = dataKey.Values["MaNhanVien"].ToString();
                    _danhMucTaiKhoan.KhoaTaiKhoan(Session["username"].ToString().Trim(), manhanvien, cb.Checked);
                }
            }
        }
    }
}